<template>
  <div>
    <el-radio-group v-model="filters.payStatus" style="margin-bottom: 30px;" @change="getSiteList(1)">
      <el-radio-button label="">全部订单</el-radio-button>
      <el-radio-button label="0">未支付<span v-if="num> 0">{{ num > 99 ?'99+': num }}</span></el-radio-button>
      <el-radio-button label="1">过期未付</el-radio-button>
      <el-radio-button label="2">已取消</el-radio-button>
      <el-radio-button label="3">已支付</el-radio-button>
      <!-- <el-radio-button label="4">退款中</el-radio-button> -->
      <el-radio-button label="5">退款成功</el-radio-button>
    </el-radio-group>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getSiteList(1)"
      @clear="clearList"
    />
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table doumee-element-tableb"
    >
      <el-table-column
        align="center"
        label="订单号"
        prop="orderId"
        width="220"
      >
        <template slot-scope="scope">
          <span class="ckxqBtn" @click="orderBtn(scope.row)"> {{ scope.row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单详情" min-width="400" prop="orderInfo" show-overflow-tooltip />
      <!-- <template slot-scope="scope">
          <span v-for="item in scope.row.siteList" :key="item.id">
            {{
              item.projectName + '-' +
                item.siteModelName +
                " " +
                item.day +
                item.beginTime +
                "~" +
                item.endTime +
                " " +
                "原价：" +
                item.price +
                " " +
                "折后价：" +
                item.memberPrice
            }}
          </span>
        </template> -->
      <el-table-column
        align="center"
        label="订单总时长"
        prop="orderAllTime"
        show-overflow-tooltip
        min-width="120"
      />
      <el-table-column
        align="center"
        label="原价总价"
        prop="allPrice"
        show-overflow-tooltip
        min-width="100"
      />
      <el-table-column
        align="center"
        label="折后总价"
        prop="realPrice"
        show-overflow-tooltip
        min-width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.realPrice || scope.row.realPrice === 0 || scope.row.realPrice === '0' ? scope.row.realPrice : scope.row.memberPrice || scope.row.memberPrice === 0 || scope.row.memberPrice === '0' ? scope.row.memberPrice :scope.row.allPrice }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="退款金额"
        prop="refundMoney"
        show-overflow-tooltip
        min-width="100"
      />
      <el-table-column
        align="center"
        label="订单来源"
        show-overflow-tooltip
        prop="channelType"
        min-width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.channelType == "01" ? "小程序" : "场馆PC端" }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="支付方式"
        prop="payMethed"
        show-overflow-tooltip
        min-width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.payMethodName || '-' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="预定人" min-width="160" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.userType == '0'">{{ scope.row.memberName? scope.row.memberName + ' ' : '' }} {{ scope.row.memberPhone || '' }}</span>
          <span v-if="scope.row.userType == '1'">{{ scope.row.userName? scope.row.userName + ' ' : '' }} {{ scope.row.userPhone || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="预定方式"
        prop="channelType"
        show-overflow-tooltip
        min-width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.userType == "0" ? "会员" : "散客" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" min-width="200" prop="remarks" show-overflow-tooltip />
      <el-table-column
        align="center"
        label="操作员"
        min-width="120"
        show-overflow-tooltip
        prop="creatorName"
      />
      <el-table-column
        align="center"
        label="创建时间"
        show-overflow-tooltip
        min-width="160"
        prop="createTime"
      />
      <el-table-column
        label="订单状态"
        prop="sort"
        min-width="100"
        show-overflow-tooltip
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          {{ scope.row.statusName }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="scope.row.status == 0 && meta.indexOf('SiteOrderPayCon') > -1"
              v-preventReClick
              type="text"
              @click="paymentShow(scope.row)"
            >继续支付</el-button>
            <el-button
              v-if="scope.row.status == 0 && meta.indexOf('SiteOrderPayCon') > -1"
              v-preventReClick
              type="text"
              @click="addShow(scope.row)"
            >增加订场</el-button>
            <el-popover
              :key="`popover-${scope.row.id}`"
              placement="bottom"
              width="120"
              class="el-pop-btns"
              trigger="hover"
            >
              <div>
                <div class="moreBtn" @click.stop="getOrderType(scope.row.orderId)">查询支付状态</div>
                <div v-if="meta.indexOf('SiteOrderPayCan') > -1" class="moreBtn" @click.stop="cancelBtn(scope.row)">取消预定</div>
              </div>
              <el-button v-if="scope.row.status == 0" slot="reference" type="text" class="moreBtnShow">更多<i class="el-icon-caret-bottom primaryColor" /></el-button>
            </el-popover>
            <el-button
              v-if="meta.indexOf('SiteOrderPayCan') > -1 && scope.row.status == 3"
              v-preventReClick
              type="text"
              @click="cancelBtn(scope.row)"
            >场地退订</el-button>
            <!-- <el-button
              v-if="scope.row.status == 3 && meta.indexOf('SiteOrderCan') > -1"
              v-preventReClick
              type="text"
              @click="unsubscribeOrderBtn(scope.row)"
            >场地退订</el-button> -->
            <el-button
              v-if="scope.row.status == 3"
              v-preventReClick
              type="text"
              @click="printOrder(scope.row.orderId)"
            >打印小票</el-button>
            <span v-if="scope.row.status == 2 || scope.row.status > 3 || scope.row.status == 1">-</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations :total="total" :page="pagination.page" :page-size="pagination.rows" @current-change="getSiteList" @SizeChange="handleSizeChange" />
    <orderDialog ref="child" @orderSuccess="getSiteList()" />
    <areaSellOrderDetail ref="areaSellOrderDetail" />
    <Replacement ref="replacement" @replacementList="replacementList" />
    <closeReserve ref="closeReserve" @closeSccess="getSiteList()" />
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import { printOrder, orderType, addReserves, allConfigList, siteOrderListPc, unsubscribeOrder, deleteUserReserveRecord } from '@/api'
import orderDialog from '@/components/order'
import QueryForm from '@/components/QueryForm'
import areaSellOrderDetail from '@/components/areaSellOrderDetail.vue'
import Replacement from '@/components/replacement.vue'
import closeReserve from '../../closeReserve.vue' // 取消
import store from '@/store'
export default {
  components: {
    orderDialog, QueryForm, areaSellOrderDetail, Replacement, closeReserve
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      authCode: '',
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: '订单编号',
          placeholder: '请输入订单编号',
          clearable: true
        }, {
          filed: 'userInfo',
          type: 'input',
          label: '客户信息',
          placeholder: '请输入姓名/手机号',
          clearable: true
        }, {
          filed: 'channelType',
          type: 'select',
          label: '订单来源',
          placeholder: '请选择订单来源',
          clearable: true,
          options: [
            { value: '01', label: '小程序' },
            { value: '02', label: '场馆PC端 ' }
          ]
        }, {
          filed: 'payMethod',
          type: 'select',
          label: '支付类型',
          placeholder: '请选择支付类型',
          clearable: true,
          options: []
        }, {
          filed: 'time',
          label: '创建时间',
          type: 'daterange',
          clearable: true
        }],
        online: true
      },
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      num: 0,
      total: 0,
      allPayMethedList: [],
      filters: {
        payStatus: ''
      },
      listLoading: false,
      loading: false,
      meta: [],
      orderId: '',
      siteIds: [],
      siteList: [],
      status: ''
    }
  },
  created() {
    this.pdgj()
    this.meta = this.$route.meta.buttons || []
  },
  methods: {
    nameWithPayMethod(payM) {
      const temp = this.allPayMethedList.find((item) => item.value === payM)
      return temp ? temp.name : '-'
    },
    replacementList(e) {
      this.siteIds = e.siteIds
      const that = this
      if (e.siteIds && e.siteIds.length > 0) {
        this.$confirm('确认增加订场, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: () => {},
          beforeClose: (action, ctx, close) => {
            if (action !== 'confirm') {
              close()
              return
            }
            ctx.confirmButtonLoading = true
            addReserves({ param: { orderId: that.orderId, siteIds: that.siteIds }}).then((res) => {
              ctx.confirmButtonLoading = false
              close()
              if (res.errorCode === '000000') {
                that.$message.success('增加订场成功')
                that.getSiteList()
              }
            })
              .catch(() => { ctx.confirmButtonLoading = false })
          }
        }).finally(() => {})
      }
    },
    addShow(row) {
      this.orderId = row.orderId
      this.$refs.replacement.showBtn(row.siteList[0].day, row.siteList[0].projectId, row.siteList, 1)
    },
    handleSizeChange(e) {
      this.pagination.rows = e
      this.getSiteList(1)
    },
    getOrderType(orderId) {
      orderType({
        param: {
          orderId
        }
      })
        .then((res) => {
          const str = res.record.msg
          if (res.errorCode === '000000') {
            if (res.record.code === '0') {
              this.$message.success(str)
              this.getSiteList()
            } else if (res.record.code === '2') {
              this.$message.info(str)
            } else {
              this.$message.error(str)
              this.getSiteList()
            }
          }
        })
    },
    printOrder(id, refundOrderId) {
      const venueId = sessionStorage.getItem('venueId')
      printOrder({
        param: {
          venueId,
          templateCode: refundOrderId ? 'SITE_REFUND_TPML' : 'SITETPML',
          workId: id,
          refundOrderId
        }
      })
        .then(res => {
          if (res.errorCode === '000000') {
            this.$message.success('打印成功')
            this.operation = false
          }
        })
    },
    pdgj() {
      allConfigList({ param: { type: '2', code: '1' }})
        .then(res => {
          if (res.errorCode !== '000000') return
          const arr = res.recordList
          arr.forEach(e => {
            e.label = e.name
          })
          this.queryFormConfig.formItems[3].options = arr
          this.allPayMethedList = arr
        })
        .catch(err => {
          console.log(err)
        })
    },
    clearList() {
      this.filters = { payStatus: '' }
      // this.$set(this.filters, 'time', [parseTime(new Date()).slice(0, 10), parseTime(new Date()).slice(0, 10)])
      this.getSiteList(1)
    },
    getSiteList(page) {
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      if (filters.time && filters.time.length > 0) {
        filters.startDate = filters.time[0] + ' 00:00:00'
        filters.endDate = filters.time[1] + ' 23:59:59'
      } else {
        filters.startDate = ''
        filters.endDate = ''
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      siteOrderListPc({ pagination, param: { venueId, ...filters }}).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.total = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getSiteList(Math.ceil(res.totalCount / pagination.rows))
          }
          this.$refs.table.doLayout()
        }
      }).catch(() => {
        this.listLoading = false
      })
      // siteOrderListPc({ pagination: {
      //   page: 1,
      //   rows: 1
      // }, param: { venueId, payStatus: '0' }}).then(res => {
      //   if (res.errorCode === '000000') {
      //     this.num = res.totalCount
      //   }
      // }).catch(() => {})
    },
    deletelBtn(e) {
      deleteUserReserveRecord({ param: { reserveAndOrderId: e.id }})
        .then(res => {
          if (res.errorCode === '000000') {
            this.$message.success('删除成功')
            this.getSiteList()
          }
        })
    },
    cancelBtn(e) {
      this.$refs.closeReserve.cancelBtn(e, [])
    },
    unsubscribeOrderBtn(e) {
      const that = this
      this.$confirm('确认场地退订, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          unsubscribeOrder({ param: { reserveAndOrderId: e.id }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('场地退订成功')
              that.getSiteList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    changePriceClick() {
      if (this.change === 0) {
        this.change = 1
      } else {
        this.change = 0
      }
    },
    paymentShow(cnt) {
      this.$refs.child.continuePay(cnt, 'areaSellOrder')
    },
    changePayMothed(item) {
      if (this.payMethod === item.value) {
        return
      }
      this.integralUse = '0'
      this.payMethod = item.value
      this.getOrderPrice()
    },
    orderBtn(row) {
      this.$refs.areaSellOrderDetail.getOrderDetail(row.id)
      // siteOrderInfo({ param: { businessId: row.id }}).then((res) => {
      //   if (res.errorCode === '000000') {
      //     this.$refs.areaSellOrderDetail.showDetail(res.record)
      //   }
      // })
    }

  }
}
</script>

